﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CRMSimple.LogService.LogServiceContext.Abstractions;
using CRMSimple.LogService.DataProducter.Abstractions;
using CRMSimple.LogService.DataConsumer.Abstractions;
using CRMSimple.LogService.DataCache.Abstractions;
using System.Threading;

namespace CRMSimple.LogService.LogServiceContext
{
    public class LogServiceContextRoot : ILogServiceContext
    {
        private IDataProducter _producter;
        private IDataConsumer _consumer;
        private IDataCache _cache;

        private bool isStop = false;
        private CancellationTokenSource cts = new CancellationTokenSource();
        private CancellationTokenSource cts1 = new CancellationTokenSource();

        private Action BuildProducterStart(IDataProducter producter, IDataConsumer consumer)
        {
            return () => {
                producter.StartProduceData(consumer.ConsumeData);
            };
        }
        private Task BuildProducterStart(IDataProducter producter, IDataCache cache)
        {
            return new Task(() =>
            {
                producter.StartProduceData(cache.Set);
            }, cts.Token);
        }
        private Action BuildProducterStop(IDataProducter producter)
        {
            return () =>
            {
                producter.StopProduceData();
                cts.Cancel();
            };
        }
        private Task BuildConsumerStart(IDataConsumer consumer, IDataCache cache)
        {
            return new Task(() =>
            {
                while (!isStop)
                {
                    cache.Get(consumer.ConsumeData);
                }
            }, cts1.Token); ;
        }

        public void SetProducter(IDataProducter producter)
        {
            this._producter = producter;
        }
        public void SetCache(IDataCache cache)
        {
            this._cache = cache;
        }
        public void SetConsumer(IDataConsumer consumer)
        {
            this._consumer = consumer;
        }

        public LogServiceContextRoot Buid()
        {
            //
            if (_producter != null && _cache != null)
            {
                this.Run= BuildProducterStart(this._producter,this._cache);
                this.Stop = BuildProducterStop(this._producter);
            }
            if (_consumer != null && _cache != null)
            {
                this.Run = BuildConsumerStart(this._consumer, this._cache);
                this.Stop = () => { this.isStop = true; cts1.Cancel(); };
            }

            return this;
        }
        public Task Run
        {
            get;
            private set;
        }
        public Action Stop
        {
            get;
            private set;
        }
    }
}
